import React from 'react';
import PropTypes from 'prop-types';
import cn from 'classnames';
import assocPath from 'ramda/es/assocPath';
import pathOr from 'ramda/es/pathOr';

import Icon from '../../../components/Icon';
import Tree from './Tree';
import s from './PortraitVis.module.css';
import HostSearchInput from '../../../components/HostSearchInput';
import CheckboxGroup from '../../../components/CheckboxGroup';
import LeafNodeInfo from './LeafNodeInfo';
import Button from '@kuiper-components/button';

const filterTypeOptions = [
	{
		label: '异常路径',
		value: 'abnormal',
	},
	{
		label: '新增路径',
		value: 'change',
	},
];

export default function PortraitVis({
	className,
	preview,
	data,
	balance,
	changeCount,
	abnormalCount,
	enableSitePortraitTriggerMonitor,
	enableMonitor,
}) {
	const [visData, changeTreeData] = React.useState({});
	const [selectedPath, setSelectedPath] = React.useState('');
	const [filterTypes, setFilterTypes] = React.useState({});
	const [nodeFilter, setNodeFilter] = React.useState('');

	React.useMemo(() => {
		let nextData = JSON.parse(JSON.stringify(data));

		const queue = [{ node: nextData, path: [], level: 0 }];
		let idx = -1;
		let notMatchNum = 0;
		let allChildren = queue.length;
		while (queue.length) {
			const { node, path, level } = queue.shift();
			nextData = assocPath(
				path,
				{
					isAbnormal: false,
					change: '',
					...node,
					hidden: false,
					isMatchFilter: false,
					path,
					level,
					id: level === 0 ? 'root' : path.join('/'),
					idx: (idx += 1),
					name: node.value,
					isChildrenExpand: level === 0,
				},
				nextData
			);

			if (node.children) {
				const nextLevel = level + 1;
				Object.entries(node.children || {}).forEach(([k, n]) => {
					allChildren++;
					queue.unshift({
						node: n,
						path: path.concat(['children', k]),
						level: nextLevel,
					});
				});
			}

			if (!nodeFilter && !filterTypes.change && !filterTypes.abnormal) {
				continue;
			}

			const isMatchFilter =
				nodeFilter &&
				(node?.value || '').toLowerCase().indexOf(nodeFilter) > -1;
			const isChanged = filterTypes.change && (node.change === 'add'); //总计时仅计数change='add'
			const isAbnormal = filterTypes.abnormal && node.isAbnormal;
			if (!isMatchFilter && !isChanged && !isAbnormal) {
				// nextData = assocPath(path.concat('hidden'), true, nextData);
				notMatchNum++;
				continue;
			}

			path.forEach((x, i) => {
				if (i % 2 === 0) return;

				const pathArr = path.slice(0, i + 1);
				const item = pathOr({}, pathArr, nextData);
				const notLeaf = i !== path.length - 1;

				nextData = assocPath(
					pathArr,
					{
						...item,
						// isAbnormal,
						hidden: false,
						isMatchFilter: notLeaf ? item.isMatchFilter : isMatchFilter,
						isChildrenExpand: notLeaf,
						// change: isChanged ? 'add' : item.change,
					},
					nextData
				);
			});
		}
		if (notMatchNum === allChildren) { // 新增没有一条满足条件数据时清空全部数据显示暂无数据场景
			delete nextData.children
		}
		changeTreeData(nextData);
	}, [data, nodeFilter, filterTypes]);

	const handleClickTreeNode = (node, type) => {
		if (type) {
			setSelectedPath(node.id);
			return;
		}
		const newNode = {
			...node,
			isChildrenExpand: !node.isChildrenExpand,
		};
		changeTreeData(
			node.path.length ? assocPath(node.path, newNode, visData) : newNode
		);
	};
	const leafNodeInfo = selectedPath === 'root' ? visData : pathOr(null, selectedPath.split('/'), visData);
	return (
		<section className={cn(className, s.portraitVis)}>
			<div className={s.toolbox}>
				<HostSearchInput
					className={s.input}
					placeholder="关键词搜索"
					value={nodeFilter}
					onChange={setNodeFilter}
				/>
				<CheckboxGroup
					options={filterTypeOptions}
					onChange={setFilterTypes}
					checked={filterTypes}
				/>
			</div>
			{balance?.sitePortrait?.total || !!data?.value ? (
				<div className={s.content}>
					<div className={s.vis}>
						<div className={s.stats}>
							{!enableMonitor && (
								<p className={s.msg}>（未开启Web漏洞网站画像监测引擎）</p>
							)}
							<div className={s.statsCount}>
								<div className={s.item}>
									<Icon className={s.icon} type="tree-change" />
									路径变动（{changeCount || 0}）
								</div>
								<div className={s.item}>
									<Icon className={s.icon} type="tree-abnormal" />
									异常路径（{abnormalCount || 0}）
								</div>
							</div>
						</div>
						<div className={cn(s.treeBox, preview && s.treeBoxOms)}>
							<Tree
								className={s.urlPatternTree}
								data={visData}
								selectedPath={selectedPath}
								onClick={handleClickTreeNode}
							/>
							{!visData?.children && <div className={s.emptyMsg}>暂无数据</div>}
						</div>
					</div>
					<LeafNodeInfo className={s.leafNodeInfo} nodeInfo={leafNodeInfo} />
				</div>
			) : (
				<div className={cn(s.content, s.emptyContent)}>
					<svg
						width="228px"
						height="151px"
						viewBox="0 0 228 151"
						version="1.1"
						xmlns="http://www.w3.org/2000/svg"
					>
						<defs>
							<linearGradient
								x1="50%"
								y1="0%"
								x2="50%"
								y2="100%"
								id="linearGradient-1"
							>
								<stop stopColor="#74CDFF" offset="0%"></stop>
								<stop stopColor="#FFFFFF" stopOpacity="0" offset="100%"></stop>
							</linearGradient>
							<circle id="path-2" cx="25" cy="25.2053287" r="25"></circle>
						</defs>
						<g
							id="网站画像"
							stroke="none"
							strokeWidth="1"
							fill="none"
							fillRule="evenodd"
						>
							<g
								id="未开通套餐备份"
								transform="translate(-717.000000, -560.000000)"
							>
								<g id="编组-10" transform="translate(717.000000, 560.000000)">
									<g
										id="编组-16"
										opacity="0.882719494"
										transform="translate(0.000000, 21.000000)"
									>
										<g id="编组-12">
											<rect
												id="矩形"
												stroke="#409EFF"
												fill="#FFFFFF"
												x="0.5"
												y="0.5"
												width="209"
												height="129"
												rx="4"
											></rect>
											<g id="编组-9">
												<path
													d="M206,0.5 L4,0.5 C3.03350169,0.5 2.15850169,0.891750844 1.52512627,1.52512627 C0.891750844,2.15850169 0.5,3.03350169 0.5,4 L0.5,15.5 L209.5,15.5 L209.5,4 C209.5,3.03350169 209.108249,2.15850169 208.474874,1.52512627 C207.841498,0.891750844 206.966498,0.5 206,0.5 Z"
													id="矩形"
													stroke="#70B6FF"
												></path>
												<g
													id="编组-21"
													transform="translate(8.000000, 5.000000)"
												>
													<circle
														id="椭圆形"
														fill="#F06761"
														cx="3"
														cy="3"
														r="3"
													></circle>
													<circle
														id="椭圆形备份"
														fill="#F9C65B"
														cx="13"
														cy="3"
														r="3"
													></circle>
													<circle
														id="椭圆形备份-2"
														fill="#71D159"
														cx="23"
														cy="3"
														r="3"
													></circle>
												</g>
											</g>
										</g>
										<g id="编组-14" transform="translate(12.000000, 24.000000)">
											<rect
												id="矩形"
												stroke="#57AAFF"
												x="0.5"
												y="0.5"
												width="185"
												height="39"
												rx="4"
											></rect>
											<path
												d="M16,33 C30.0331352,9.63086899 45.3055469,2.64522651 61.8172352,12.0430725 C78.7082326,21.6568074 86.099113,26.7225442 96.3584062,26.7600586 C101.142474,26.7775522 106.550279,24.9429595 113.835995,20.5 C127.330837,11.562243 158.218549,14.1805909 165.425012,21.8324955 C170.22932,26.9337652 173.754316,30.6562667 176,33 L16,33 Z"
												id="路径-2"
												fill="url(#linearGradient-1)"
											></path>
										</g>
										<g id="编组-15" transform="translate(12.000000, 70.000000)">
											<g
												id="编组-11"
												transform="translate(0.000000, 6.205329)"
												fill="#5CACFF"
											>
												<rect
													id="矩形备份-3"
													x="0"
													y="0.794671281"
													width="124"
													height="7"
													rx="2"
												></rect>
												<rect
													id="矩形备份-4"
													x="0"
													y="15.7946713"
													width="89"
													height="7"
													rx="2"
												></rect>
												<rect
													id="矩形备份-5"
													x="0"
													y="30.7946713"
													width="58"
													height="7"
													rx="2"
												></rect>
											</g>
											<g
												id="路径-6"
												transform="translate(136.000000, 0.000000)"
											>
												<mask id="mask-3" fill="white">
													<use></use>
												</mask>
												<circle
													stroke="#57AAFF"
													cx="25"
													cy="25.2053287"
													r="24.5"
												></circle>
												<polygon
													fill="#70B6FF"
													mask="url(#mask-3)"
													points="25 25.2053287 34.356857 -1 57.2934266 9.73015332 56.3918163 19.8380202"
												></polygon>
											</g>
										</g>
									</g>
									<g id="编组-23" transform="translate(178.000000, 0.000000)">
										<rect
											id="矩形"
											stroke="#57AAFF"
											fill="#FFFFFF"
											x="0.5"
											y="0.5"
											width="49"
											height="59"
											rx="4"
										></rect>
										<g
											id="编组-22"
											transform="translate(6.000000, 10.000000)"
											fill="#85D3FF"
										>
											<rect
												id="矩形备份-2"
												x="0"
												y="0"
												width="38"
												height="4"
												rx="2"
											></rect>
											<rect
												id="矩形备份-8"
												x="0"
												y="12"
												width="38"
												height="4"
												rx="2"
											></rect>
											<rect
												id="矩形备份-9"
												x="0"
												y="24"
												width="38"
												height="4"
												rx="2"
											></rect>
											<rect
												id="矩形备份-10"
												x="0"
												y="36"
												width="38"
												height="4"
												rx="2"
											></rect>
										</g>
										<g
											id="编组-13"
											transform="translate(13.000000, 15.000000)"
											fillRule="nonzero"
										>
											<path
												d="M24,4.3327178 L22.8312912,4.3327178 C22.8312912,4.3327178 20.1034919,4.25108698 17.3769049,3.12834882 C14.571031,1.92523373 12.6996336,0.561369523 12.6996336,0.561369523 L11.9993838,0 L11.2979161,0.480993487 C11.2979161,0.480993487 9.43017843,1.84611454 6.62430453,3.04797278 C3.89772615,4.25108786 1.17114776,4.25108786 1.17114776,4.25108786 L0,4.25108786 L0,16.9252293 C0,23.2623 7.79179246,30 11.9993753,30 C16.2081875,30 24,23.2623 24,16.9252293 L24,4.33147273 L24,4.3327178 Z"
												id="形状"
												fill="#51A4F9"
											></path>
											<g
												id="实时"
												transform="translate(6.000000, 4.500000)"
												fill="#FFFFFF"
											>
												<path
													d="M5.52304688,1.14500765 L1.0281121,8.44927666 C0.690991998,9.12351688 1.14048547,10.0225038 2.03947242,10.0225038 L5.52304688,10.0225038 L4.73643329,18.3381331 C4.73643329,18.7876266 5.29830014,19.0123734 5.52304688,18.5628799 L10.0179817,9.46063698 C10.3551018,8.78639676 9.90560828,7.8874098 9.1189947,7.8874098 L5.41067351,7.8874098 L6.1972871,1.3697544 C6.30966046,0.920260934 5.74779363,0.695514182 5.52304688,1.14500765 Z"
													id="路径"
												></path>
											</g>
										</g>
									</g>
								</g>
							</g>
						</g>
					</svg>
					<h3>基于云防御防护日志，智能可视化网站路径分析</h3>
					<div>
						<a
							target="_blank"
							rel="noreferrer"
							href="https://url.cn/5F3cNO5?_type=wpa&qidian=true"
						>
							<Button primary>立即咨询</Button>
						</a>
					</div>
				</div>
			)}
		</section>
	);
}

PortraitVis.propTypes = {
	className: PropTypes.string,
	hostUrl: PropTypes.string,
	changeCount: PropTypes.number.isRequired,
	abnormalCount: PropTypes.number.isRequired,
	data: PropTypes.shape({
		value: PropTypes.string.isRequired,
		children: PropTypes.object.isRequired,
	}).isRequired,
	preview: PropTypes.bool,
	balance: PropTypes.shape({
		sitePortrait: PropTypes.shape({
			value: PropTypes.string,
		}),
	}),
	enableMonitor: PropTypes.bool.isRequired,
	enableSitePortraitTriggerMonitor: PropTypes.bool,
};

PortraitVis.defaultProps = {
	className: s.portrait,
	data: {},
	preview: false,
	changeCount: 0,
	abnormalCount: 0,
	enableSitePortraitTriggerMonitor: false,
};
